package com.projectdemo.springbootdemo1.controller;

import com.projectdemo.springbootdemo1.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HomeController {

    /**
     * 欢迎页面
     *
     * @param model 模型
     * @return java.lang.String data
     * @date 2024/10/24
     * @author zhangzw
     **/
    @GetMapping("/thymeleafDemo")
    public String home(Model model) {
        model.addAttribute("message", "Welcome to Thymeleaf with Spring Boot!");
        Student user = new Student("学生张三",23);
        model.addAttribute("user", user);
        List<Student> items = new ArrayList<>();
        items.add(user);
        items.add(new Student("学生李四",12));
        model.addAttribute("items", items);
        return "thymeleafDemo";
    }

    /**
     * 表单提交绑定
     *
     * @param model 模型
     * @param user 用户对象
     * @return java.lang.String data
     * @date 2024/10/24
     * @author zhangzw
     **/
    @PostMapping("/submit")
    public String submit(Model model,@ModelAttribute Student user) {
        System.out.println(user.toString());
        return "thymeleafDemo";
    }

    @RequestMapping(value = "/")
    public String first(Model model){
        model.addAttribute("lang","zh-CN");
        return "login";
    }
    @RequestMapping(value = {"/{language}/login","/{language}/login.html"},method = RequestMethod.GET)
    public String loginPage(@PathVariable("language") String lang,Model model){
        model.addAttribute("lang",lang);
        return "login";
    }
    @RequestMapping(value = {"/{language}/index","/{language}/index.html"},method = RequestMethod.GET)
    public String index(@PathVariable("language") String lang,Model model){
        model.addAttribute("lang",lang);
        return "index";
    }
    @RequestMapping(value = "/{language}/loginvalid",method = RequestMethod.POST)
    public String loginValid(@RequestParam("username") String username, @RequestParam("password") String password, Model model,
                             HttpSession session, @PathVariable("language") String lang){
        model.addAttribute("lang",lang);
        if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
            session.setAttribute("username",username);
            return "redirect:index.html";
        }else{
            model.addAttribute("msg","用户名密码错误!");
            return "login";
        }
    }
}
